//
//  DownView.m
//  GiftSay
//
//  Created by dllo on 16/1/12.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "DownView.h"
#import "ShowArrayCollectionViewCell.h"
#import "ShowArrayCollectionViewCellTwo.h"
#import "hiddenView.h"
@interface DownView ()<UICollectionViewDataSource, UICollectionViewDelegate, dele, hiddendele>
@property (nonatomic,strong) NSIndexPath *end;
@property (nonatomic,assign) NSIndexPath *indext;
@property (nonatomic, strong) hiddenView *hiddenView;
//隐藏数组
@property (nonatomic, strong) NSMutableArray *hiddenArray;
@end

@implementation DownView
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}
//数据直通车
-(void)setDataArray:(NSArray *)dataArray {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"NightModeOpen" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"NightModeOff" object:nil];
    _dataArray = dataArray;
//    从本地获取
    NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:[self saveArray]];
//    [array2 removeAllObjects];
    
    
    if (array2.count > 0) {
        self.showArray = [[NSMutableArray alloc] initWithArray:array2];
    } else {
        self.showArray = [[NSMutableArray alloc] initWithArray:self.dataArray];
    }
    
    
    
    
    self.hiddenArray = [[NSMutableArray alloc] initWithCapacity:0];
    [self compareArray];
    UIView *downViewSelect = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width - self.width / 10.3, self.width / 10.3)];
    downViewSelect.tag = 1000;
    [self addSubview:downViewSelect];
    self.chang = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width / 5, downViewSelect.height)];
    self.chang.text = @"切换频道";
    self.chang.textColor = [UIColor blackColor];
    self.chang.textAlignment = NSTextAlignmentCenter;
    self.chang.font = [UIFont systemFontOfSize:14 * SCREEN_WIDTH];
    [downViewSelect addSubview:self.chang];
    self.done = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.done setTitle:@"排序或删除" forState:UIControlStateNormal];
    self.done.titleLabel.font = [UIFont systemFontOfSize:14 * SCREEN_WIDTH];
    self.done.frame = CGRectMake(downViewSelect.width - self.chang.width, 0, self.width / 5, downViewSelect.height);
    [self.done setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.done addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchDown];
    [downViewSelect addSubview:self.done];
    
//    收录数组视图
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    NSInteger width = [self collectionWidth];
    layout.itemSize = CGSizeMake(width / 4, width / 4 / 2);
    
    float height = [self collectionHeight:self.showArray];

    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, downViewSelect.height, width, height) collectionViewLayout:layout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.collection registerClass:[ShowArrayCollectionViewCell class] forCellWithReuseIdentifier:@"ShowArrayCollectionViewCell"];
    [self.collection registerClass:[ShowArrayCollectionViewCellTwo class] forCellWithReuseIdentifier:@"ShowArrayCollectionViewCellTwo"];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongGesture:)];
    [self.collection addGestureRecognizer:longPressGesture];
    [self addSubview:self.collection];
    
//    hiddenView
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:self.dataArray];
    float height2 = [self collectionHeight:array];
    self.hiddenView = [[hiddenView alloc] initWithFrame:CGRectMake(0, self.collection.frame.origin.y + self.collection.height, self.width, height2 + self.width / 10.3)];
    self.hiddenView.delegate = self;
    if (self.hiddenArray.count > 0) {
        self.hiddenView.frame = CGRectMake(0, self.collection.frame.origin.y + self.collection.height, self.width, height2 + self.width / 10.3);
        self.hiddenView.alpha = 1;
    } else {
        self.hiddenView.frame = CGRectZero;
        self.hiddenView.alpha = 0;
    }
    self.hiddenView.dataArray = self.hiddenArray;
    [self addSubview:self.hiddenView];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.backgroundColor = kNightModeColor;
        self.collection.backgroundColor = kNightModeColor;
        self.chang.textColor = [UIColor whiteColor];
        downViewSelect.backgroundColor = kNightModeColor;
        
        ;
    } else {
        self.backgroundColor = [UIColor whiteColor];
        self.collection.backgroundColor = [UIColor whiteColor];
        self.chang.textColor = [UIColor blackColor];
        downViewSelect.backgroundColor = [UIColor whiteColor];
    }
    
}
- (void)refresh {
    UIView *view = [self viewWithTag:1000];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        view.backgroundColor = kNightModeColor;
        self.backgroundColor = kNightModeColor;
        self.collection.backgroundColor = kNightModeColor;
        self.chang.textColor = [UIColor whiteColor];
    } else {
        view.backgroundColor = [UIColor whiteColor];
        self.backgroundColor = [UIColor whiteColor];
        self.chang.textColor = [UIColor blackColor];
        self.collection.backgroundColor = [UIColor whiteColor];
    }
    [self.collection reloadData];
}

#pragma mark -- 计算collection高度
-(CGFloat)collectionHeight:(NSMutableArray *)array {
    NSInteger width = [self collectionWidth];
    float height;
    if (array.count % 4 == 0) {
        height = array.count / 4 * (width / 4 / 2);
    } else {
        height = (array.count / 4 + 1) * (width / 4 / 2);
    }
    return height;
}
#pragma mark -- 计算collection宽度
-(NSInteger)collectionWidth {
    int width;
    if ((NSInteger)self.width % 4 == 0) {
        width = self.width;
    } else {
        width = self.width / 4 * 4;
    }
    return width;
}

#pragma mark -- collectionview协议
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.ifDone == NO) {
        ShowArrayCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShowArrayCollectionViewCell" forIndexPath:indexPath];
        cell.name = self.showArray[indexPath.item];
        return cell;
    } else if(self.ifDone == YES){
        ShowArrayCollectionViewCellTwo *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShowArrayCollectionViewCellTwo" forIndexPath:indexPath];
        if (indexPath.item == 0) {
            cell.ifcell = YES;
        }
        else{
            cell.ifcell = NO;
        }
        
        cell.delegate = self;
        cell.name = self.showArray[indexPath.item];
        return cell;
    }else{
        return nil;
    }
}

-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0) {
        return NO;
    }
    return self.ifDone;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ShowArrayCollectionViewCell *cell = (ShowArrayCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"%@", cell.name);
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.showArray.count;
}

- (void)handleLongGesture:(UILongPressGestureRecognizer *)gesture
{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            
            self.indext = [self.collection indexPathForItemAtPoint:[gesture locationInView:self.collection]];
            [self.collection beginInteractiveMovementForItemAtIndexPath:self.indext];
            break;
        case UIGestureRecognizerStateChanged:
            
            [self.collection updateInteractiveMovementTargetPosition:[gesture locationInView:gesture.view]];
            break;
        case UIGestureRecognizerStateEnded:
        
            [self.collection endInteractiveMovement];
            self.end = [self.collection indexPathForItemAtPoint:[gesture locationInView:self.collection]];
            if (self.end.row == 0) {
                [self.showArray insertObject:self.showArray[self.indext.row] atIndex:self.end.row + 1];
                [self.showArray removeObjectAtIndex:self.indext.row + 1];
            } else if (self.indext.row > self.end.row) {
                [self.showArray insertObject:self.showArray[self.indext.row] atIndex:self.end.row];
                [self.showArray removeObjectAtIndex:self.indext.row + 1];
            } else if (self.indext.row < self.end.row) {
                [self.showArray insertObject:self.showArray[self.indext.row] atIndex:self.end.row + 1];
                [self.showArray removeObjectAtIndex:self.indext.row];
            }
            [self.collection reloadData];
            break;
            
        default:
            [self.collection cancelInteractiveMovement];
            
            break;
    }
}

//排序按钮
-(void)done:(UIButton *)sender {
    if (self.ifDone == NO) {
        self.ifDone = YES;
        [self.collection reloadData];
        [self.done setTitle:@"完成" forState:UIControlStateNormal];
        self.chang.text = @"拖拽排序";
    } else {
        self.ifDone = NO;
        [self.collection reloadData];
        [self.done setTitle:@"排序或删除" forState:UIControlStateNormal];
        self.chang.text = @"切换频道";
        
        NSLog(@"%@",self.showArray);
        
    }
}
#pragma mark -- 删除按钮返回协议方法
-(void)dele:(NSString *)name {
    for (int i = 0; i < self.showArray.count; i++) {
        if ([self.showArray[i] isEqualToString:name]) {
            [self.showArray removeObjectAtIndex:i];
        }
    }
    float height = [self collectionHeight:self.showArray];
    self.collection.height = height;
    [self.hiddenArray removeAllObjects];
    [self compareArray];
    [self.collection reloadData];
}

-(void)hiddendele:(NSString *)name {
    [self.hiddenArray removeObject:name];
    [self.showArray insertObject:name atIndex:self.showArray.count];
    [self.collection reloadData];
    [self.hiddenView.collection reloadData];
    
    float height = [self collectionHeight:self.showArray];
    self.collection.height = height;
    if (self.hiddenArray.count > 0) {
        float height = [self collectionHeight:self.hiddenArray];
        self.hiddenView.frame = CGRectMake(0, self.collection.frame.origin.y + self.collection.height, self.width, height + self.width / 10.3);
        self.hiddenView.alpha = 1;
    } else {
        self.hiddenView.frame = CGRectZero;
        self.hiddenView.alpha = 0;
    }
}

#pragma mark --  对比数组
-(void)compareArray {
//    网络请求总数据对比本地存储数据
    int num = 0;
    for (int j = 0; j < self.dataArray.count; j++) {
        for (int i = 0; i < self.showArray.count; i++) {
            if (![self.showArray[i] isEqualToString:self.dataArray[j]]) {
                num++;
                if (num == self.showArray.count) {
                    [self.hiddenArray addObject:self.dataArray[j]];
                    num = 0;
                }
            }
        }
        num = 0;
    }
    if (self.hiddenArray.count > 0) {
        float height = [self collectionHeight:self.hiddenArray];
        self.hiddenView.frame = CGRectMake(0, self.collection.frame.origin.y + self.collection.height, self.width, height + self.width / 10.3);
        self.hiddenView.alpha = 1;
    } else {
        self.hiddenView.frame = CGRectZero;
        self.hiddenView.alpha = 0;
    }
    self.hiddenView.dataArray = self.hiddenArray;
}
#pragma mark -- 本地取数组
-(NSArray *)saveArray {
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
    NSString *newFielPath = [documentsPath stringByAppendingPathComponent:@"aa.txt"];
    return [NSArray arrayWithContentsOfFile:newFielPath];
}



@end
